package com.example.javapracticaltraining.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.javapracticaltraining.entity.R;
import com.example.javapracticaltraining.entity.pojo.PerformanceEvaluation;
import com.example.javapracticaltraining.entity.pojo.MedicalStaff;
import com.example.javapracticaltraining.service.PerformanceEvaluationService;
import com.example.javapracticaltraining.service.MedicalStaffService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 医护人员绩效评估管理控制器
 */
@RestController
@RequestMapping("/evaluations")
@Tag(name = "绩效评估管理", description = "医护人员绩效评估的增删改查操作")
public class PerformanceEvaluationController {

    @Autowired
    private PerformanceEvaluationService evaluationService;

    @Autowired
    private MedicalStaffService medicalStaffService;

    /**
     * 获取所有绩效评估
     * @return 绩效评估列表
     */
    @Operation(summary = "获取所有绩效评估", description = "返回系统中所有医护人员的绩效评估列表")
    @ApiResponse(responseCode = "200", description = "成功获取绩效评估列表")
    @GetMapping
    public R<List<PerformanceEvaluation>> getAllEvaluations() {
        List<PerformanceEvaluation> evaluations = evaluationService.list();
        return R.success(evaluations);
    }

    /**
     * 分页获取绩效评估
     * @param page 页码
     * @param pageSize 每页大小
     * @param staffId 医护人员ID（可选，用于筛选）
     * @param startMonth 开始月份（可选，用于筛选）
     * @param endMonth 结束月份（可选，用于筛选）
     * @return 分页后的绩效评估列表
     */
    @Operation(summary = "分页获取绩效评估", description = "根据条件分页查询绩效评估，支持按医护人员ID和月份范围筛选")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功获取分页绩效评估列表")
    })
    @GetMapping("/page")
    public R<Page<PerformanceEvaluation>> getEvaluationsByPage(
            @Parameter(description = "页码，默认为1") @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页记录数，默认为10") @RequestParam(defaultValue = "10") int pageSize,
            @Parameter(description = "医护人员ID，可选参数") Integer staffId,
            @Parameter(description = "开始月份，可选参数，格式：yyyy-MM-dd") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startMonth,
            @Parameter(description = "结束月份，可选参数，格式：yyyy-MM-dd") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endMonth) {

        Page<PerformanceEvaluation> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<PerformanceEvaluation> queryWrapper = new LambdaQueryWrapper<>();

        if (staffId != null) {
            queryWrapper.eq(PerformanceEvaluation::getStaffId, staffId);
        }

        if (startMonth != null) {
            queryWrapper.ge(PerformanceEvaluation::getEvaluationMonth, startMonth);
        }

        if (endMonth != null) {
            queryWrapper.le(PerformanceEvaluation::getEvaluationMonth, endMonth);
        }

        // 默认按评估月份倒序排序
        queryWrapper.orderByDesc(PerformanceEvaluation::getEvaluationMonth);

        evaluationService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 根据ID获取绩效评估
     * @param evaluationId 评估ID
     * @return 绩效评估信息
     */
    @Operation(summary = "根据ID获取绩效评估", description = "根据评估ID获取绩效评估详细信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功获取绩效评估信息"),
        @ApiResponse(responseCode = "404", description = "未找到该绩效评估")
    })
    @GetMapping("/{evaluationId}")
    public R<PerformanceEvaluation> getEvaluation(@Parameter(description = "绩效评估ID") @PathVariable Integer evaluationId) {
        PerformanceEvaluation evaluation = evaluationService.getById(evaluationId);
        if (evaluation != null) {
            return R.success(evaluation);
        }
        return R.failure(404, "未找到该绩效评估");
    }

    /**
     * 获取指定医护人员的绩效评估
     * @param staffId 医护人员ID
     * @return 绩效评估列表
     */
    @Operation(summary = "获取指定医护人员的绩效评估", description = "根据医护人员ID获取其所有绩效评估记录")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功获取医护人员的绩效评估列表"),
        @ApiResponse(responseCode = "404", description = "未找到该医护人员")
    })
    @GetMapping("/staff/{staffId}")
    public R<List<PerformanceEvaluation>> getEvaluationsByStaff(@Parameter(description = "医护人员ID") @PathVariable Integer staffId) {
        // 检查医护人员是否存在
        MedicalStaff staff = medicalStaffService.getById(staffId);
        if (staff == null) {
            return R.failure(404, "未找到该医护人员");
        }

        LambdaQueryWrapper<PerformanceEvaluation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PerformanceEvaluation::getStaffId, staffId)
                   .orderByDesc(PerformanceEvaluation::getEvaluationMonth);

        List<PerformanceEvaluation> evaluations = evaluationService.list(queryWrapper);
        return R.success(evaluations);
    }

    /**
     * 获取指定月份的绩效评估
     * @param month 月份（格式：yyyy-MM）
     * @return 绩效评估列表
     */
    @Operation(summary = "获取指定月份的绩效评估", description = "根据月份获取所有医护人员在该月的绩效评估记录")
    @ApiResponse(responseCode = "200", description = "成功获取指定月份的绩效评估列表")
    @GetMapping("/month/{month}")
    public R<List<PerformanceEvaluation>> getEvaluationsByMonth(
            @Parameter(description = "月份，格式：yyyy-MM-dd") @PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate month) {

        LambdaQueryWrapper<PerformanceEvaluation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PerformanceEvaluation::getEvaluationMonth, month)
                   .orderByDesc(PerformanceEvaluation::getTotalScore);

        List<PerformanceEvaluation> evaluations = evaluationService.list(queryWrapper);
        return R.success(evaluations);
    }

    /**
     * 添加新的绩效评估
     * @param evaluation 绩效评估信息
     * @return 操作结果
     */
    @Operation(summary = "添加绩效评估", description = "创建新的医护人员绩效评估记录")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "绩效评估添加成功"),
        @ApiResponse(responseCode = "404", description = "未找到相关医护人员"),
        @ApiResponse(responseCode = "400", description = "该医护人员在所选月份已有绩效评估")
    })
    @PostMapping
    public R<String> addEvaluation(@RequestBody PerformanceEvaluation evaluation) {
        // 检查医护人员是否存在
        MedicalStaff staff = medicalStaffService.getById(evaluation.getStaffId());
        if (staff == null) {
            return R.failure(404, "未找到该医护人员");
        }

        // 检查是否已存在同月份同医护人员的评估
        LambdaQueryWrapper<PerformanceEvaluation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PerformanceEvaluation::getStaffId, evaluation.getStaffId())
                   .eq(PerformanceEvaluation::getEvaluationMonth, evaluation.getEvaluationMonth());

        PerformanceEvaluation existingEvaluation = evaluationService.getOne(queryWrapper);
        if (existingEvaluation != null) {
            return R.failure(400, "该医护人员在所选月份已有绩效评估");
        }

        // 计算总分（如果未提供）
        if (evaluation.getTotalScore() == null) {
            double totalScore = 0;
            int count = 0;

            if (evaluation.getQualityScore() != null) {
                totalScore += evaluation.getQualityScore();
                count++;
            }

            if (evaluation.getEfficiencyScore() != null) {
                totalScore += evaluation.getEfficiencyScore();
                count++;
            }

            if (evaluation.getTeamworkScore() != null) {
                totalScore += evaluation.getTeamworkScore();
                count++;
            }

            if (evaluation.getSkillScore() != null) {
                totalScore += evaluation.getSkillScore();
                count++;
            }

            if (count > 0) {
                evaluation.setTotalScore(totalScore / count);
            }
        }

        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        evaluation.setCreateTime(now);
        evaluation.setUpdateTime(now);

        evaluationService.save(evaluation);
        return R.success("绩效评估添加成功");
    }

    /**
     * 更新绩效评估信息
     * @param evaluation 绩效评估信息
     * @return 操作结果
     */
    @Operation(summary = "更新绩效评估", description = "根据ID更新医护人员绩效评估信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "绩效评估更新成功"),
        @ApiResponse(responseCode = "400", description = "绩效评估ID不能为空或该医护人员在所选月份已有其他绩效评估"),
        @ApiResponse(responseCode = "404", description = "未找到相关绩效评估或医护人员")
    })
    @PutMapping
    public R<String> updateEvaluation(@RequestBody PerformanceEvaluation evaluation) {
        // 检查是否存在
        if (evaluation.getEvaluationId() == null) {
            return R.failure(400, "绩效评估ID不能为空");
        }

        PerformanceEvaluation existingEvaluation = evaluationService.getById(evaluation.getEvaluationId());
        if (existingEvaluation == null) {
            return R.failure(404, "未找到该绩效评估");
        }

        // 检查医护人员是否存在
        MedicalStaff staff = medicalStaffService.getById(evaluation.getStaffId());
        if (staff == null) {
            return R.failure(404, "未找到该医护人员");
        }

        // 检查是否已存在同月份同医护人员的其他评估
        LambdaQueryWrapper<PerformanceEvaluation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PerformanceEvaluation::getStaffId, evaluation.getStaffId())
                   .eq(PerformanceEvaluation::getEvaluationMonth, evaluation.getEvaluationMonth())
                   .ne(PerformanceEvaluation::getEvaluationId, evaluation.getEvaluationId());

        PerformanceEvaluation duplicateEvaluation = evaluationService.getOne(queryWrapper);
        if (duplicateEvaluation != null) {
            return R.failure(400, "该医护人员在所选月份已有其他绩效评估");
        }

        // 计算总分（如果未提供）
        if (evaluation.getTotalScore() == null) {
            double totalScore = 0;
            int count = 0;

            if (evaluation.getQualityScore() != null) {
                totalScore += evaluation.getQualityScore();
                count++;
            }

            if (evaluation.getEfficiencyScore() != null) {
                totalScore += evaluation.getEfficiencyScore();
                count++;
            }

            if (evaluation.getTeamworkScore() != null) {
                totalScore += evaluation.getTeamworkScore();
                count++;
            }

            if (evaluation.getSkillScore() != null) {
                totalScore += evaluation.getSkillScore();
                count++;
            }

            if (count > 0) {
                evaluation.setTotalScore(totalScore / count);
            }
        }

        // 保留原创建时间，更新更新时间
        evaluation.setCreateTime(existingEvaluation.getCreateTime());
        evaluation.setUpdateTime(LocalDateTime.now());

        evaluationService.updateById(evaluation);
        return R.success("绩效评估更新成功");
    }

    /**
     * 删除绩效评估
     * @param evaluationId 绩效评估ID
     * @return 操作结果
     */
    @Operation(summary = "删除绩效评估", description = "根据ID删除医护人员绩效评估")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "绩效评估删除成功"),
        @ApiResponse(responseCode = "404", description = "未找到相关绩效评估")
    })
    @DeleteMapping("/{evaluationId}")
    public R<String> deleteEvaluation(@Parameter(description = "绩效评估ID") @PathVariable Integer evaluationId) {
        // 检查是否存在
        PerformanceEvaluation existingEvaluation = evaluationService.getById(evaluationId);
        if (existingEvaluation == null) {
            return R.failure(404, "未找到该绩效评估");
        }

        // 执行删除操作
        evaluationService.removeById(evaluationId);
        return R.success("绩效评估删除成功");
    }
}
